package com.qgs.rabbitmqapi.returnListener;

import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * @Author: 蔡翔
 * @Date: 2019/7/19 13:27
 * @Version 1.0
 */
public class Producer {
    public static void main(String[] args) throws Exception {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.0.229");
        connectionFactory.setVirtualHost("/");
        connectionFactory.setPort(5672);

        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();

        String exchange = "test_return_exchange";
        String routingKey = "return.save";
        String routingKeyError = "abc.save";
        String queueName = "test_return_queue";

        String msg = "hello rabbitmq returnListener";
        channel.basicPublish(exchange,routingKeyError,true,null,msg.getBytes()); //这里就算匹配不到路由，也会把消息投递到ReturnListener。
        //总结来说producter投递消息到exchange后找不到匹配队列后，就会投递到addReturnListener(new ReturnListener())里面去。
        //channel.basicPublish(exchange,routingKeyError,false,null,msg.getBytes()); //達不到路由匹配，就會把那條消息給刪除
        //channel.basicPublish(exchange,routingKey,true,null,msg.getBytes());  //這個是正常路由到信息的。

        channel.addReturnListener(new ReturnListener() { //来接受路由不可达消息。
            @Override
            public void handleReturn(int replyCode, String replyText, String exchange, String routingKey, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("---------handle return-------------");
                //用这个方法来处理消息不得达的消息。                System.out.println("replyCode："+replyCode);
                System.out.println("replyText："+replyText);
                System.out.println("exchange："+exchange);
                System.out.println("routingKey："+routingKey);
                System.out.println("properties："+properties);
                System.out.println("body："+new String(body));
            }
        });
    }
}
